package com.web.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Http请求获取开奖数据
 * 
 * @author yangzhongying mail:223450427@qq.com
 * @date 2016-11-10 下午02:29:40
 * @package com.web.utils
 */
public class HttpTest {

	// name 彩种名称 GET 必填 参考下方 name 参数列表
	// uid 用户ID GET 必填 ***** 登录获取
	// token 通信验证 GET 必填 ***** 登录获取
	// format 输出格式 GET 选填 json 或 json3 或 xml 或 xml2 或 xml5
	// num 条数设置 GET 选填 10（默认：10条，支持：1~50条）
	// date 日期搜索 GET 选填 20161110
	// order 期号排序 GET 选填 sort（默认为降序，sort为升序）
	
	//开发
	//public static String pkUrl = "http://api.caipiaokong.com/lottery/?name=bjpks&format=json&uid=647822&token=563552642ff06cdf70154839c41cee87b4ec73b5&num=3";
	//生产
	public static String pkUrl = "http://api.kaijiangtong.com/lottery/?name=bjpks&format=json&uid=621060&token=c7aad5d342d62c9cb27278cf979a621357edacfc&num=3";
	
	public static String charset = "UTF-8";
	
//	public static void main(String[] args){
//		get(pkUrl,charset);
//	}

	/**
	 * @param urlAll
	 *            :请求接口
	 * @param charset
	 *            :字符编码
	 * @return 返回json结果
	 */
	public static String get(String urlAll, String charset) {
		BufferedReader reader = null;
		String result = null;
		StringBuffer sbf = new StringBuffer();
		String userAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36";// 模拟浏览器
		InputStream is=null;
		try {
			URL url = new URL(urlAll);
			HttpURLConnection connection = (HttpURLConnection) url
					.openConnection();
			connection.setRequestMethod("GET");
			connection.setReadTimeout(15000);
			connection.setConnectTimeout(15000);
			connection.setRequestProperty("User-agent", userAgent);
			connection.connect();
			is = connection.getInputStream();
			reader = new BufferedReader(new InputStreamReader(is, charset));
			String strRead = null;
			while ((strRead = reader.readLine()) != null) {
				sbf.append(strRead);
				sbf.append("\r\n");
			}
			reader.close();
			result = sbf.toString();
		} catch (Exception e) {
			//String json = HttpRequest.get(HttpRequest.pkUrl, HttpRequest.charset);
			e.printStackTrace();
			//System.out.println("===="+json);
			return null;
		}finally{
			if(is!=null){
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return result;
	}
}